package ltd.hxya.novel.rabbitmq.aspect;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import ltd.hxya.novel.common.anno.SaveNotice;
import ltd.hxya.novel.common.bean.BaseEntity;
import ltd.hxya.novel.common.bean.OperEnum;
import ltd.hxya.novel.common.constant.rabbit.RabbitConstant;
import ltd.hxya.novel.common.to.notice.Notice;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class NoticeAspect {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Pointcut("@annotation(saveNotice)")
    public void notice(SaveNotice saveNotice){}

    @Around(value = "notice(saveNoticeAnno)")
    public void noticeAspect(ProceedingJoinPoint joinPoint,SaveNotice saveNoticeAnno) throws Throwable {
        //在方法执行之前，如果方法的参数中，不携带id，则添加id，如果携带id，则取出其中的id

        OperEnum operEnum = saveNoticeAnno.operEnum();
        if (operEnum.code == OperEnum.SAVE.getCode()){
            //执行新增的处理
            save(joinPoint,saveNoticeAnno);
        }
        if (operEnum.code == OperEnum.UPDATE.getCode()){

        }
        if (operEnum.code == OperEnum.UPDATE.getCode()){

        }

    }

    private void save(ProceedingJoinPoint joinPoint, SaveNotice saveNoticeAnno) throws Throwable {
        joinPoint.proceed();
        Object[] args = joinPoint.getArgs();
        String operId = null;
        for (Object arg : args) {

            if (arg instanceof BaseEntity){
                operId = ((BaseEntity) arg).getOperId();
            }
        }
        Notice notice = new Notice();
        notice.setNoticeType(OperEnum.SAVE.code);
        if (StringUtils.isEmpty(operId)){
            return;
        }
        notice.setOperationId(operId);
        generateNotice(saveNoticeAnno,notice);
    }

    private void generateNotice(SaveNotice saveNoticeAnno, Notice notice) {
        notice.setNoticeMessage(saveNoticeAnno.message());
        notice.setModuleKey(saveNoticeAnno.module().key);
        notice.setModuleName(saveNoticeAnno.module().getModuleName());
        notice.setNoticeId(IdWorker.getIdStr());
        notice.setCreateTime(LocalDateTime.now());
        notice.setCreateTime(LocalDateTime.now());
        log.debug(JSON.toJSONString(notice));
        rabbitTemplate.convertAndSend(RabbitConstant.ADMIN_NOTICE_EXCHANGE,RabbitConstant.ADMIN_NOTICE_ROUTING_KEY,notice);
    }

}
